package yf.mall.service.impl;

import com.github.pagehelper.PageHelper;
import yf.mall.common.Const;
import com.yf.service.impl.BaseServiceImpl;
import yf.mall.dao.*;
import yf.mall.entity.*;
import yf.mall.enums.MallActStatusEnum;
import yf.mall.enums.MallGoodsShelfEnum;
import yf.mall.service.MallStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import yf.mall.service.MallGoodsService;
import org.springframework.transaction.annotation.Transactional;
import yf.mall.vo.TicketVo;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 产品Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Mon Aug 05 11:33:59 CST 2019
 */
@Service
public class MallGoodsServiceImpl extends BaseServiceImpl<MallGoodsEntity> implements MallGoodsService {

    private MallGoodsDao mallGoodsDao;

    @Autowired
    private MallStoreService mallStoreService;

    @Autowired
    private StockRecordDao stockRecordDao;


    @Autowired
    public void setDao(MallGoodsDao mallGoodsDao) {
        this.mallGoodsDao = mallGoodsDao;
        super.setBaseDao(mallGoodsDao);
    }


    /**
     * 内部方法
     **/

    //过滤一些字段不让前端知道
    private List<MallGoodsEntity> apiFilter(List<MallGoodsEntity> mallGoodsEntities) {
        mallGoodsEntities.forEach(mallGoodsEntity -> apiFilter(mallGoodsEntity));
        return mallGoodsEntities;
    }

    //过滤一些字段不让前端知道
    private MallGoodsEntity apiFilter(MallGoodsEntity mallGoodsEntity) {
        mallGoodsEntity.setProfit(null);
        return mallGoodsEntity;
    }


    /**
     * 外部方法实现
     **/


    @Autowired
    private MallSkuThemeDao mallSkuThemeDao;

    @Autowired
    private MallSkuItemDao mallSkuItemDao;

    @Autowired
    private MallSkuDao mallSkuDao;

    @Autowired
    private PriceDao priceDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private LevelDao levelDao;

    @Autowired
    private MallActDao mallActDao;

    //更新产品并且更新Sku
    @Override
    @Transactional(rollbackFor = Exception.class)
    public MallGoodsEntity merge(MallGoodsEntity mallGoodsEntity) {
        if (mallGoodsEntity.getId() != null) {//update
            mallGoodsDao.update(mallGoodsEntity);
            //删除主题 外键会自动删除Item
            mallSkuThemeDao.deleteByGoodsId(mallGoodsEntity.getId());
            //清除所有的sku
            mallSkuDao.deleteByGoodsId(mallGoodsEntity.getId());
        } else { //save保存
            mallGoodsDao.save(mallGoodsEntity);
        }
        //更新Sku TODO 引起库存的问题 库存用增量的方式修改
        List<MallSkuThemeEntity> skuThemes = mallGoodsEntity.getSkuThemes();
        if (skuThemes != null && skuThemes.size() > 0) {
            //实体化skuTheme
            mallSkuThemeDao.saveList(skuThemes, mallGoodsEntity.getId());
            for (MallSkuThemeEntity skuTheme : skuThemes) {
                //实体化skuItem
                if (skuTheme.getItems().size() > 0) {
                    mallSkuItemDao.saveList(skuTheme.getItems(), skuTheme.getId());
                }
            }
        }
        List<MallSkuEntity> skuEntities = mallGoodsEntity.getMallSkus();
        if (skuEntities != null && skuEntities.size() > 0) {
            mallSkuDao.saveList(mallGoodsEntity.getMallSkus(), mallGoodsEntity.getId());
        }
        //更新价格
        for (PriceEntity priceEntity : mallGoodsEntity.getPrices()) {
            //更新
            if (priceEntity.getId() == null) {
                priceEntity.setGoodsId(mallGoodsEntity.getId());
                priceDao.save(priceEntity);
            } else {
                priceDao.update(priceEntity);
            }
        }
        return mallGoodsEntity;
    }


    @Override
    public MallGoodsEntity getWithSku(Long goodsId) {
        MallGoodsEntity mallGoodsEntity = mallGoodsDao.get(goodsId);
        List<MallSkuThemeEntity> themeEntities = mallSkuThemeDao.queryListByGoodsId(mallGoodsEntity.getId());
        for (MallSkuThemeEntity skuThemeEntity : themeEntities) {
            List<MallSkuItemEntity> itemEntities = mallSkuItemDao.queryListBySkuId(skuThemeEntity.getId());
            skuThemeEntity.setItems(itemEntities);
        }
        mallGoodsEntity.setSkuThemes(themeEntities);
        List<MallSkuEntity> mallSkuEntities = mallSkuDao.queryListByGoodsId(goodsId);
        mallGoodsEntity.setMallSkus(mallSkuEntities);
        return mallGoodsEntity;
    }


    @Override
    public List<MallGoodsEntity> topList(int limit, int page) {
        PageHelper.startPage(page, limit);
        HashMap param = new HashMap();
        //只查上架了的
        param.put("shelf", MallGoodsShelfEnum.ON.getIndex());
        param.put("order", "sort");
        List<MallGoodsEntity> mallGoodsEntities = mallGoodsDao.queryList(param);
        return apiFilter(mallGoodsEntities);
    }

    @Override
    public MallGoodsEntity getDetail(Long goodsId) {
        MallGoodsEntity mallGoodsEntity = getWithSku(goodsId);
        return apiFilter(mallGoodsEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MallGoodsEntity updateStock(StockRecordEntity stockRecordEntity) {
        String skuName = stockRecordEntity.getSkuName();
        //产品规格存在 更新sku相关信息 同步更新总数
        if (skuName != null && !skuName.equals("")) {
            if (stockRecordEntity.getQuantity() > 0) {
                mallGoodsDao.increaseStock(stockRecordEntity.getGoodsId(), stockRecordEntity.getQuantity());
                mallGoodsDao.increaseSkuStock(stockRecordEntity.getGoodsId(), stockRecordEntity.getSkuName(), stockRecordEntity.getQuantity());
            } else {
                mallGoodsDao.decreaseStock(stockRecordEntity.getGoodsId(), stockRecordEntity.getQuantity());
                mallGoodsDao.decreaseSkuStock(stockRecordEntity.getGoodsId(), stockRecordEntity.getSkuName(), stockRecordEntity.getQuantity());
            }
        } else { //产品规格不存在  更新产品库存 跟公司账户库存
            if (stockRecordEntity.getQuantity() > 0) {
                mallGoodsDao.increaseStock(stockRecordEntity.getGoodsId(), stockRecordEntity.getQuantity());
                //增加公司账户库存
                mallStoreService.increase(Const.ADMIN_ID, stockRecordEntity.getGoodsId(), stockRecordEntity.getQuantity());
            } else {
                mallGoodsDao.decreaseStock(stockRecordEntity.getGoodsId(), stockRecordEntity.getQuantity());
                //减少公司账户库存
                mallStoreService.decrease(Const.ADMIN_ID, stockRecordEntity.getGoodsId(), stockRecordEntity.getQuantity());
            }
        }
        //保存记录
        stockRecordDao.save(stockRecordEntity);
        return mallGoodsDao.get(stockRecordEntity.getGoodsId());
    }

    @Override //quequnlong
    public List<MallGoodsEntity> findGoods() {
        return mallGoodsDao.findGoods(MallGoodsShelfEnum.ON.getIndex());
    }

    @Override   //根据标签id查询
    public List<MallGoodsEntity> findBySaleType(Map<String, Object> map,Long type) {
        List<MallGoodsEntity> list = new ArrayList<>();
        Integer saleType = (Integer) map.get("saleType"); //获取功能区id
        if (null != type && type != 0) { //判断是否是首页  为true则不是首页
            //获取一级分类的所有二级分类
            List<MallTypeEntity> mallTypeEntityList = mallTypeDao.findByParentId(type);
            if (mallTypeEntityList.size() > 0 && null != mallTypeEntityList) {
                for (MallTypeEntity typeEntity : mallTypeEntityList) {
                    //根据分类获取产品id
                    List<Long> goodsId = mallTypeDao.findByTypeId(typeEntity.getId());
                    if (null != goodsId && goodsId.size() > 0) {
                        for (Long goodId : goodsId) {
                            //获取产品
                            MallGoodsEntity goodsEntity = mallGoodsDao.get(goodId);
                            if (null != goodsEntity && goodsEntity.getSaleType() == saleType && goodsEntity.getShelf() == MallGoodsShelfEnum.ON.getIndex()) {
                                list.add(goodsEntity);
                            }
                        }
                    }
                }
            }
            return list;
        }
            return mallGoodsDao.findBySaleType(map);
}


    @Override
    public List<MallGoodsEntity> filterByLevel(Long userId, List<MallGoodsEntity> mallGoodsEntities) {
        return mallGoodsEntities.stream().filter(mallGoodsEntity -> {
            MallActEntity mallActEntity = mallActDao.findByGoodsIdAndstatus(mallGoodsEntity.getId(), MallActStatusEnum.OPEN.getIndex());

            if (mallActEntity != null && mallActEntity.getOpen()) {
                UserEntity userEntity = userDao.get(userId);
                LevelEntity levelEntity = levelDao.get(userEntity.getLevelId());
                // 限制了当前级别
                if (mallActEntity.getLevel() != null && !mallActEntity.getLevel().equals("") && mallActEntity.getLevel().contains(levelEntity.getName())) {
                    return false;
                }
            }

            return true;
        }).collect(Collectors.toList());
    }

    @Autowired
    private MallTypeDao mallTypeDao;

    @Override  //根据分类id查询产品
    public List<MallGoodsEntity> queryMallGoods(Map<String, Object> map) {
        Long typeId = (Long) map.get("typeId");
        List<MallGoodsEntity> list = new ArrayList<>();
        List<Long> goods = mallTypeDao.findByTypeId(typeId);
        if (goods.size() > 0 && null != goods) {
            for (Long goodId : goods) {
                MallGoodsEntity mallGoodsEntity = mallGoodsDao.get(goodId);
                if (mallGoodsEntity.getShelf() != null && MallGoodsShelfEnum.ON.getIndex() == mallGoodsEntity.getShelf()) {
                    list.add(mallGoodsEntity);
                }
            }
        }
        //排序  quequnlong
        Collections.sort(list, (o1,o2) -> {
            if ( null!= o1.getSort() && null != o2.getSort()){
                if (o1.getSort() > o2.getSort()){
                    return 1;
                }
            }
                return -1;
        });
        return list;
    }

    @Override  //根据产品名查询
    public List<MallGoodsEntity> searchName(String name) {
        return mallGoodsDao.searchName(name, MallGoodsShelfEnum.ON.getIndex());
    }

}


